package setup

import (
	"github.com/facebookgo/inject"
	"github.com/shinedone/srv-framework/pkg/asserts"
	"github.com/shinedone/srv-framework/pkg/beans"
	"github.com/shinedone/srv-server/internal/global/instance"
	grpc2 "github.com/shinedone/srv-server/internal/modules/enterprise/grpc"
	"google.golang.org/grpc"
	"net"
)

// grpc初始化
func GrpcInit(errc chan error) {
	config := instance.GetConfig()
	kitLog := instance.GetKitLog()

	// 监听端口
	grpcAddress := config.Grpc.Address
	lis, err := net.Listen("tcp", grpcAddress)
	asserts.Nil(err, err)
	// 初始化grpc服务
	var opts []grpc.ServerOption
	// 设置通用拦截器

	grpcServer := grpc.NewServer(opts...)
	// 注册grpc服务
	registerGrpcServer(grpcServer)
	// 启动grpc服务器
	go func() {
		_ = kitLog.Log("transport", "GRPC", "addr", grpcAddress)
		errc <- grpcServer.Serve(lis)
	}()
}

// 注册grpc服务
func registerGrpcServer(grpcServer *grpc.Server) {
	// 初始化grpcService
	enterpriseGrpcService := &grpc2.GrpcService{}
	err := beans.Provide(&inject.Object{Value: enterpriseGrpcService})
	asserts.Nil(err, err)
	err = beans.Populate()
	asserts.Nil(err, err)

	grpc2.RegisterEnterpriseGrpcServer(grpcServer, enterpriseGrpcService)
}
